package com.deng.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.deng.common.lang.Result;
import com.deng.entity.User;
import com.deng.util.ValidationUtil;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.Security;

@Controller
public class AuthController extends BaseController{
    @Autowired
    Producer producer;
    private static final String KAPTCHA_SESSION="yzm";
    @GetMapping("/kaptcha.jpg")
    public void kaptcha(HttpServletResponse resp) throws IOException {
        String text=producer.createText();
        req.getSession().setAttribute(KAPTCHA_SESSION,text);
        BufferedImage image=producer.createImage(text);
        resp.setHeader("Cache-Control","no-store,no-cache");
        resp.setContentType("image/jpeg");
        ServletOutputStream outputStream=resp.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
    }
    @GetMapping("/login")
    public String login(){
        return "/auth/login";
    }
    @PostMapping("/login")
    @ResponseBody
    public Result doLogin(String email,String password){
        if(StrUtil.isEmpty(email)||StrUtil.isEmpty(password)){
            return Result.fail("邮箱密码不能为空");
        }
        //shiro里面的Token,数据库里存的是md5加密的password
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(email, SecureUtil.md5(password));
        //shiro登录
        try{
            SecurityUtils.getSubject().login(usernamePasswordToken);
        }catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return Result.fail("用户不存在");
            } else if (e instanceof LockedAccountException) {
                return Result.fail("用户被禁用");
            } else if (e instanceof IncorrectCredentialsException) {
                return Result.fail("密码错误");
            } else {
                return Result.fail("用户认证失败");
            }
        }

        return Result.success().action("/");
    }
    @PostMapping("/register")
    @ResponseBody
    public Result doRegister(User user,String repass,String vercode){
        //用户名密码邮箱不能为空
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(user);
        if(validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }
        if(!user.getPassword().equals(repass)){
            return Result.fail("两次输入的密码不相同");
        }
        String kaptcha=(String)req.getSession().getAttribute(KAPTCHA_SESSION);
        if(vercode==null ||!vercode.equalsIgnoreCase(kaptcha)){
            return Result.fail("验证码输入不正确");
        }
        Result result=userService.register(user);
        return result.success().action("/login");
    }
    @GetMapping("/register")
    public String register(){
        return "/auth/reg";
    }
    @RequestMapping("/user/logout")
    public String logout(){
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }
}
